package com.lixun.passwordbook.slice;

import com.lixun.passwordbook.ResourceTable;
import com.lixun.passwordbook.pojo.Colors;
import com.lixun.passwordbook.pojo.Constant;
import com.lixun.passwordbook.pojo.Data;
import com.lixun.passwordbook.util.AESUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ListDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DetailedAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(3, 0xD001100, "DetailedStart");
    private static final String BASE_URI = "dataability:///com.lixun.passwordbook.DataAbility";
    private static final String DATA_PATH = "/pwb";
    private static final String DB_COLUMN_ID = "id";
    private static final String DB_COLUMN_NICKNAME = "nickname";
    private static final String DB_COLUMN_USERNAME = "username";
    private static final String DB_COLUMN_PASSWOED = "password";
    private static final String DB_COLUMN_TYPE = "type";
    private static final String DB_COLUMN_EXPLAIN = "explain";
    private static final String DB_COLUMN_MODIFYTIME = "modifytime";
    public static final int DIALOG_BOX_WIDTH = 300;
    public static final int DIALOG_BOX_HEIGHT = 700;
    private Data data;
    private int id;
    private String updateBtnText;
    private String deleteBtnText;
    private DataAbilityHelper databaseHelper;
    private Context mContext;

    @Override
    public void onStart(Intent intent) {
        HiLog.info(LABEL,"onStart");
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_detailed);
        mContext = this;
        databaseHelper = DataAbilityHelper.creator(this);
        //获取传递的id值
        id = intent.getIntParam("id",-1);
        if (id == 0){
            updateBtnText = "添加";
            deleteBtnText = "重置";
            //清除页面数据
            clearData();
        } else {
            updateBtnText = "修改";
            deleteBtnText = "删除";
            //添加页面数据
            setData();
        }
        //设置标题
        Text text = (Text)findComponentById(ResourceTable.Id_detailed_text);
        text.setText(updateBtnText);
        //创建修改|添加按钮
        createUpadteBtn();
        //创建删除|重置按钮
        createDeleteBtn();
        //创建选择类型按钮
        createTypeBtn();
        //创建返回按钮
        createReturnBtn();
        //设置状态栏颜色
        setStatusBarColor();
        //设置颜色模式
        colorMode();
    }

    @Override
    public void onActive() {
        super.onActive();

    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 设置状态栏颜色
     */
    private void setStatusBarColor() {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        getWindow().setStatusBarColor(Color.TRANSPARENT.getValue());
    }

    /**
     * 设置颜色模式
     */
    private void colorMode(){
        DirectionalLayout abilityDetailed = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed);
        DirectionalLayout item1 = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed_item1);
        DirectionalLayout item2 = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed_item2);
        DirectionalLayout item3 = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed_item3);
        DirectionalLayout item4 = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed_item4);
        DirectionalLayout item5 = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_detailed_item5);
        TextField textField = (TextField)findComponentById(ResourceTable.Id_detailed_explain);
        Text nickname = (Text)findComponentById(ResourceTable.Id_detailed_nickname);
        Button type = (Button)findComponentById(ResourceTable.Id_detailed_type);
        Text username = (Text)findComponentById(ResourceTable.Id_detailed_username);
        Text password = (Text)findComponentById(ResourceTable.Id_detailed_password);
        Text text = (Text)findComponentById(ResourceTable.Id_detailed_text);
        Text text1 = (Text)findComponentById(ResourceTable.Id_detailed_text1);
        Text text2 = (Text)findComponentById(ResourceTable.Id_detailed_text2);
        Text text3 = (Text)findComponentById(ResourceTable.Id_detailed_text3);
        Text text4 = (Text)findComponentById(ResourceTable.Id_detailed_text4);
        Text text5 = (Text)findComponentById(ResourceTable.Id_detailed_text5);
        Button returnBtn = (Button)findComponentById(ResourceTable.Id_detailed_return);
        boolean dark_mode = Colors.getDarkMode();
        ShapeElement shapeElement = new ShapeElement();
        ShapeElement element;
        ShapeElement elementTextFiled;
        Color color;
        Resource bgResource=null;
        if (dark_mode){
            HiLog.info(LABEL, "设置为深色模式");
            shapeElement.setRgbColor(Colors.backgroundColorDark);
            element = new ShapeElement(mContext,ResourceTable.Graphic_item_background_dark);
            elementTextFiled = new ShapeElement(mContext,ResourceTable.Graphic_detailed_text_field_dark);
            color = Colors.textColorDark;
        } else {
            HiLog.info(LABEL, "设置为常规模式");
            shapeElement.setRgbColor(Colors.backgroundColor);
            element = new ShapeElement(mContext,ResourceTable.Graphic_item_background);
            elementTextFiled = new ShapeElement(mContext,ResourceTable.Graphic_detailed_text_field);
            color = Colors.textColor;
        }
        try {
            if (dark_mode){
                bgResource =getResourceManager().getResource(ResourceTable.Media_detailed_return_dark);
            } else {
                bgResource =getResourceManager().getResource(ResourceTable.Media_detailed_return);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        abilityDetailed.setBackground(shapeElement);
        item1.setBackground(element);
        item2.setBackground(element);
        item3.setBackground(element);
        item4.setBackground(element);
        item5.setBackground(element);
        textField.setTextColor(color);
        nickname.setTextColor(color);
        type.setTextColor(color);
        username.setTextColor(color);
        password.setTextColor(color);
        text.setTextColor(color);
        text1.setTextColor(color);
        text2.setTextColor(color);
        text3.setTextColor(color);
        text4.setTextColor(color);
        text5.setTextColor(color);
        PixelMapElement pixBg=new PixelMapElement(bgResource);
        returnBtn.setAroundElements(pixBg,null,null,null);
    }

    /**
     * 设置页面数据
     */
    private void setData(){
        queryid();
        Text nickname1 = (Text)findComponentById(ResourceTable.Id_detailed_nickname);
        nickname1.setText(data.getNickname());
        Button type1 = (Button)findComponentById(ResourceTable.Id_detailed_type);
        type1.setText(data.getType());
        Text uesrname1 = (Text)findComponentById(ResourceTable.Id_detailed_username);
        uesrname1.setText(data.getUsername());
        Text password1 = (Text)findComponentById(ResourceTable.Id_detailed_password);
        password1.setText(data.getPassword());
        Text explain1 = (Text)findComponentById(ResourceTable.Id_detailed_explain);
        explain1.setText(data.getExplain());
    }

    /**
     * 清空页面数据
     */
    private void clearData(){
        Text nickname1 = (Text)findComponentById(ResourceTable.Id_detailed_nickname);
        nickname1.setText("");
        Button type1 = (Button)findComponentById(ResourceTable.Id_detailed_type);
        type1.setText("默认");
        Text uesrname1 = (Text)findComponentById(ResourceTable.Id_detailed_username);
        uesrname1.setText("");
        Text password1 = (Text)findComponentById(ResourceTable.Id_detailed_password);
        password1.setText("");
        Text explain1 = (Text)findComponentById(ResourceTable.Id_detailed_explain);
        explain1.setText("");
    }

    /**
     * 创建类型选择按钮
     */
    private void createTypeBtn(){
        Component component = findComponentById(ResourceTable.Id_detailed_type);
        Button typeSelect;
        if (component instanceof Button) {
            typeSelect = (Button) component;
            typeSelect.setClickedListener(view -> {
                showListDialog(typeSelect);
            });
        }
    }

    /**
     * 设置返回按钮
     */
    private void createReturnBtn(){
        Component component = findComponentById(ResourceTable.Id_detailed_return);
        Button typeSelect;
        if (component instanceof Button) {
            typeSelect = (Button) component;
            typeSelect.setClickedListener(view -> {
                terminate();
            });
        }
    }

    /**
     * 创建修改|添加按钮
     */
    private void createUpadteBtn(){
        Component component = findComponentById(ResourceTable.Id_detailed_update);
        Button updateBtn;
        if (component instanceof Button) {
            updateBtn = (Button) component;
            updateBtn.setText(updateBtnText);
            updateBtn.setClickedListener(view -> {
                clickUpdateBth();
            });
        }
    }

    /**
     * 创建删除|重置按钮
     */
    private void createDeleteBtn(){
        Component component = findComponentById(ResourceTable.Id_detailed_delete);
        Button deleteBtn;
        if (component instanceof Button) {
            deleteBtn = (Button) component;
            deleteBtn.setText(deleteBtnText);
            deleteBtn.setClickedListener(view -> {
                clickDeleteBth();
            });
        }
    }

    /**
     * 点击修改|添加按钮出发功能
     */
    private void clickUpdateBth(){
        TextField nickname = (TextField) findComponentById(ResourceTable.Id_detailed_nickname);
        Button type = (Button)findComponentById(ResourceTable.Id_detailed_type);
        TextField username = (TextField)findComponentById(ResourceTable.Id_detailed_username);
        TextField password = (TextField)findComponentById(ResourceTable.Id_detailed_password);
        TextField explain = (TextField)findComponentById(ResourceTable.Id_detailed_explain);
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String modifytime = time.format(new Date());// new Date()为获取当前系统时间
        data = new Data(id,nickname.getText(),username.getText(),password.getText(),type.getText(),explain.getText(),modifytime);
        String results = "失败";
        if (id == 0){
            if (insert()){
                results = "成功";
            };
        } else {
            if (update()){
                results = "成功";
            };
        }
        new ToastDialog(this)
                .setText(updateBtnText+results)
                // 显示在界面底部
                .setAlignment(LayoutAlignment.BOTTOM)
                .show();
        terminate();
    }

    /**
     * 点击删除|重置按钮出发功能
     */
    private void clickDeleteBth(){
        String results = "失败";
        if (id == 0){
            clearData();
            results = "成功";
        } else {
            if (delete()){
                results = "成功";
                terminate();
            };
        }
        new ToastDialog(this)
                .setText(deleteBtnText+results)
                // Toast显示在界面底部
                .setAlignment(LayoutAlignment.BOTTOM)
                .show();
    }

    /**
     * 设置类型选择器
     * @param type 类型
     */
    private void showListDialog(Button type) {
        String[] types = new String[]{"       默 认", "       网 站", "       游 戏", "       邮 箱","       APP"};
        String[] types1 = new String[]{"默认", "网站", "游戏","邮箱","APP"};
        ListDialog listDialog = new ListDialog(this);
        listDialog.setAlignment(TextAlignment.CENTER);
        listDialog.setSize(DIALOG_BOX_WIDTH, DIALOG_BOX_HEIGHT);
        listDialog.setTitleText("  选择类型");
        listDialog.setCornerRadius(50);
        listDialog.setAutoClosable(true);
        listDialog.setItems(types);
        listDialog.setOnSingleSelectListener((iDialog, index) -> {
            type.setText(types1[index]);
            iDialog.destroy();
        });
        listDialog.show();
    }

    /**
     * 查询指定id
     */
    private void queryid() {
        String[] columns = new String[] { DB_COLUMN_NICKNAME, DB_COLUMN_USERNAME, DB_COLUMN_PASSWOED,DB_COLUMN_TYPE,DB_COLUMN_EXPLAIN,DB_COLUMN_MODIFYTIME};
        // 构造查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo(DB_COLUMN_ID, id);
        try {
            ResultSet resultSet = databaseHelper.query(Uri.parse(BASE_URI + DATA_PATH),
                    columns, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                HiLog.info(LABEL, "query: resultSet is null or no result found");
            }
            resultSet.goToFirstRow();
            String nickname = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_NICKNAME));
            String username = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_USERNAME));
            String bytepwd = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_PASSWOED));
            String password;
            //如果密码未设置，则不经过转换，否则会出现错误提示app正常运行
            if (bytepwd == null || bytepwd.length() ==0 || bytepwd.equals("")){
                password = bytepwd;
            } else {
                password = AESUtils.decrypt(Constant.getKEY(),bytepwd);
            }
            String type = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_TYPE));
            String explain = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_EXPLAIN));
            data = new Data(nickname,username,password,type,explain);
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "query: dataRemote exception | illegalStateException");
        }
    }

    /**
     * 修改
     * @return 判断是否修改成功
     */
    private Boolean update() {
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo(DB_COLUMN_ID, id);
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString(DB_COLUMN_NICKNAME, data.getNickname());
        valuesBucket.putString(DB_COLUMN_USERNAME, data.getUsername());
        String password = data.getPassword();
        if (password == null || password.length() == 0){
        } else {
            password = AESUtils.encrypt(Constant.getKEY(),password);
        }
        valuesBucket.putString(DB_COLUMN_PASSWOED, password);
        valuesBucket.putString(DB_COLUMN_TYPE, data.getType());
        valuesBucket.putString(DB_COLUMN_EXPLAIN, data.getExplain());
        valuesBucket.putString(DB_COLUMN_MODIFYTIME, data.getModifytime());
        try {
            if (databaseHelper.update(Uri.parse(BASE_URI + DATA_PATH), valuesBucket, predicates) != -1) {
                HiLog.info(LABEL, "update 成功");
                return true;
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "update: dataRemote exception | illegalStateException");
        }
        return false;
    }

    /**
     * 添加
     * @return 判断是否添加成功
     */
    private Boolean insert(){
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString(DB_COLUMN_NICKNAME, data.getNickname());
        valuesBucket.putString(DB_COLUMN_USERNAME, data.getUsername());
        String password = data.getPassword();
        if (password == null || password.length() == 0){
        } else {
            password = AESUtils.encrypt(Constant.getKEY(),password);
        }
        valuesBucket.putString(DB_COLUMN_PASSWOED, password);
        valuesBucket.putString(DB_COLUMN_TYPE, data.getType());
        valuesBucket.putString(DB_COLUMN_EXPLAIN, data.getExplain());
        valuesBucket.putString(DB_COLUMN_MODIFYTIME, data.getModifytime());
        try {
            if (databaseHelper.insert(Uri.parse(BASE_URI + DATA_PATH), valuesBucket) != -1) {
                HiLog.info(LABEL, "insert 成功");
                return true;
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "insert: dataRemote exception|illegalStateException");
        }
        return false;
    }

    /**
     * 删除
     * @return 判断是否删除成功
     */
    private boolean delete() {
        DataAbilityPredicates predicates = new DataAbilityPredicates()
                .equalTo(DB_COLUMN_ID, id);
        try {
            if (databaseHelper.delete(Uri.parse(BASE_URI + DATA_PATH), predicates) != -1) {
                HiLog.info(LABEL, "delete 成功");
                return true;
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "delete: dataRemote exception | illegalStateException");
        }
        return false;
    }
}
